package com.woohua.thread.life;

/***
 * @title LifeCycleDemo
 * @description:生命周期
 * @author woo hua
 * @version 1.0.0
 * @create 2023/3/10 13:18
 **/
public class LifeCycleDemo {

    public static void main(String[] args) {
        Thread t0 = new Thread(new Runnable() {
            @Override
            public void run() {
                Counter.increase();
            }
        });

        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                Counter.increase();
            }
        });

        // 创建后状态为 NEW
        printState(t0);
        printState(t1);

        t0.start();
        t1.start();

        // 启动后状态为 RUNNABLE
        printState(t0);
        printState(t1);

        sleep(1000);

        // 运行后 t0 获得同步锁，进入代码块执行 Thread.sleep 后状态变更为 TIMED_WAITING
        printState(t0);
        // t1 等待获取同步锁，状态为 BLOCKED
        printState(t1);

        sleep(4000);

        // 线程执行完后状态为 TERMINATED (结束)
        printState(t0);
        printState(t1);

        System.out.println("count: " + Counter.getCount());
    }

    private static void printState(Thread t) {
        System.out.println(t.getName() + " " + t.getState());
    }

    private static void sleep(long millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
